<?php

namespace App\Exceptions;

use Closure;
use Exception;
use Illuminate\Database\Eloquent\Model;

class ApiException extends Exception
{
    /**
     * 转换异常为 HTTP 响应
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request) {
        // DB::rollBack(); // 尝试回滚
        return response($this->getMessage() ?: '发生异常啦~');
    }

    /** 异常快捷抛出, 保持json响应 */
    public static function throw_str(mixed $result, ?Closure $exCallback=null): mixed {
        if ($result && is_string($result)) {
            $exCallback && $exCallback($result);
            throw new ApiException($result);
        }
        return $result;
    }

}